package com.cyj.dream.admin.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyj.dream.admin.model.request.SysUserQueryRequest;
import com.cyj.dream.admin.model.system.SysUser;
import com.cyj.dream.admin.persistence.manager.systems.SysUserManager;
import com.cyj.dream.admin.service.system.SysUserService;
import com.cyj.dream.core.constant.pagemodel.PageParam;
import com.cyj.dream.core.util.IsEmptyUtils;
import com.cyj.dream.core.util.nosql.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 系统用户业务层实现类
 * @BelongsProject: dream-DreamChardonnay
 * @BelongsPackage: com.dream.DreamChardonnay.service.impl
 * @Author: ChenYongJia
 * @CreateTime: 2021-04-02 09:23
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysUserManager sysUserManager;

    /**
     * 分页查询系统用户信息
     *
     * @param pageParam 分页参数以及入参
     * @return com.dream.DreamChardonnay.constant.model.PageWrapper<com.dream.DreamChardonnay.model.vo.SysUserVo>
     * @date 2021/4/17 10:47
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public IPage<SysUser> list(PageParam<SysUserQueryRequest> pageParam) {
        Page<SysUser> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        IPage<SysUser> dbPage = sysUserManager.list(page, pageParam.getParam());
        return dbPage;
    }

    /**
     * 查询系统用户信息
     *
     * @param queryRequest 入参参数
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysUser>
     * @date 2021/5/15 10:23
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public List<SysUser> findBySysUserInfo(SysUserQueryRequest queryRequest) {
        return sysUserManager.findBySysUserInfo(queryRequest);
    }

    /**
     * 查询系统所有用户信息
     *
     * @return java.util.List<com.dream.DreamChardonnay.model.system.SysUser>
     * @date 2021/6/17 10:22
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public List<SysUser> findAll() {
        return sysUserManager.findAll();
    }

    /**
     * 根据用户id查询用户
     *
     * @param sysUserId 用户id
     * @return com.dream.DreamChardonnay.model.system.SysUser
     * @date 2021-5-19 14:23:54
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public SysUser findBySysUserId(Long sysUserId) {
        return sysUserManager.findBySysUserId(sysUserId);
    }

    /**
     * 添加用户信息
     *
     * @param sysUser 用户对象
     * @return boolean
     * @date 2021/4/21 9:26
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public boolean addUserInfo(SysUser sysUser) {
        log.info("添加用户信息， sysUser 为=======>{}", JSONObject.toJSONString(sysUser));
        return sysUserManager.addUserInfo(sysUser);
    }

    /**
     * 逻辑删除用户信息
     *
     * @param sysUser 用户对象
     * @return boolean
     * @date 2021/4/21 9:26
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public boolean delUserInfo(List<SysUser> sysUser) {
        return sysUserManager.delUserInfo(sysUser);
    }

    /**
     * 根据用户名称查询用户
     *
     * @param sysUserName
     * @return com.dream.DreamChardonnay.model.system.SysUser
     * @date 2021/4/2 9:47
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public SysUser findBySysUserName(String sysUserName) {
        return sysUserManager.selectByUserName(sysUserName);
    }

    /**
     * 修改用户详情
     *
     * @param sysUser
     * @return java.lang.String
     * @date 2021/4/2 9:47
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public boolean updUserPassWord(SysUser sysUser) {
        return sysUserManager.updateSysUser(sysUser);
    }

    /**
     * 修改用户详情--不含登录修改
     *
     * @param sysUser 用户对象
     * @return boolean
     * @date 2021-6-9 14:16:22
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public boolean updateSysUserCloud(SysUser sysUser) {
        return sysUserManager.updateSysUserCloud(sysUser);
    }

    /**
     * 根据token获取用户信息（根据 key 去 Redis 获取 value）
     *
     * @param token token值
     * @return com.dream.DreamChardonnay.model.system.SysUser
     * @date 2021/4/17 9:36
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    @Transactional
    public SysUser getSysUserByToken(String token) {
        log.info("根据token获取用户信息（根据 key 去 Redis 获取 value）， token 为=======>{}", token);

        try {
            Object object = redisUtil.get(token);

            SysUser userInfo = sysUserManager.findBySysUserId(Long.parseLong(object.toString()));
            /*if (!IsEmptyUtils.isEmpty(userInfo.getUserInfoDepartmentId())) {

                Department departments = depService.findByDepartmentId(userInfo.getUserInfoDepartmentId());
                Department departmentParent = depService.findByDepartmentId(departments.getDepartmentParentId());
                userInfo.setUserInfoDepartmentName(departmentParent.getDepartmentName() + "/" + departments.getDepartmentName());*/
            if (IsEmptyUtils.isEmpty(object)) {
                return null;
            } else {
                return userInfo;
            }
            /*} else {
                return null;
            }*/
        } catch (Exception e) {
            log.error("从 redis 获取数据失败，原因为：" + e);
        }
        return null;
    }

    /**
     * 根据token退出登录（根据 key 去 Redis 删除 value） 0 成功 1 失败
     *
     * @param token token值
     * @return java.lang.Integer
     * @date 2021/4/17 9:36
     * @author ChenYongJia
     * @version 1.0
     */
    @Override
    public Integer loginOutByToken(String token) {
        log.info("根据token退出登录（根据 key 去 Redis 删除 value）， token 为=======>{}", token);

        try {
            // 先判断是否存在
            Object delFlag = redisUtil.get(token);
            if (!ObjectUtil.isEmpty(delFlag)) {
                // 再判断是否已经过了过期时间
                long result = redisUtil.getExpire(token);
                // 等于 0 未过期直接移除
                if (result == 0) {
                    redisUtil.del(token);
                    return 0;
                } else {
                    redisUtil.del(token);
                    return 0;
                }
            } else {
                return 0;
            }
        } catch (Exception e) {
            log.error("从 redis 删除数据失败，原因为：" + e);
        }
        return 0;
    }

}
